import java.util.*;

public class Solution791 {
    public String customSortString(String order, String s) {
        int[] map = new int[26];
        for (int i = 0; i < order.length(); i++) {
            map[order.charAt(i) - 'a'] = i+1;
        }
        List<Character> sortChars = new ArrayList<>(s.length());
        StringBuilder res = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            char tmpChar = s.charAt(i);
            if(map[tmpChar - 'a'] != 0){
                sortChars.add(tmpChar);
            }
            else{
                res.append(tmpChar);
            }
        }
        Collections.sort(sortChars, new Comparator(){
            @Override
            public int compare(Object o1, Object o2) {
                return map[(char)o1-'a'] - map[(char)o2-'a'];
            }
        });
        for (Character character:sortChars) {
            res.append(character);
        }
        return res.toString();
    }

    public static void main(String[] args) {
        Solution791 s = new Solution791();
        System.out.println(s.customSortString("cba", "abcd"));
    }
}
